<?php

namespace App\Admin\Controllers\XinYou;

use App\Admin\Actions\Post\UpdateGuildWithdrawFail;
use App\Admin\Actions\Post\UpdateGuildWithdrawOk;
use App\Admin\Actions\Post\UpdateGuildWithdrawOkXmi;
use App\Admin\Exports\WithdrawExport;
use App\Admin\Extensions\GuildWithdrawVerify;
use App\Http\Controllers\Controller;
use App\Model\Guild\GuildBalance;
use App\Model\Guild\GuildManage;
use App\Model\Guild\GuildWithdrawal;
use App\Model\Message;
use App\Model\User;
use App\Util\YzhUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GuildWithdrawController extends Controller
{
    use ModelForm;

    /**
     * 请求操作的id
     * @var array|Application|Request|string
     */
    private $id;

    /**
     * 操作的状态
     * @var array|Application|Request|string
     */
    private $status;

    /**
     * 操作
     * @var array|Application|Request|string
     */
    private $payWay;

    /**
     * 操作的记录
     * @var
     */
    private $record;


    /**
     * 页面数据
     * @return Content
     */
    public function index(): Content
    {
        $this->isAdmin = Admin::user()->inRoles(['administrator']);
        return Admin::content(function (Content $content) {
            $content->header('推广员提现审核');
            $yzhAccount = YzhUtil::queryAccounts();
            if (!isset($yzhAccount['data'])) $info = '';
            else {
                $actBalance = $yzhAccount['data']['dealer_infos'][0]['acct_balance'];
                $rebateBalance = $yzhAccount['data']['dealer_infos'][0]['rebate_fee_balance'];
                $info = "云账户余额：{$actBalance}；返点余额：{$rebateBalance}  <span style='margin-right: 2rem;'></span>  |";
            }

            $content->description($info);
            $adminId = Admin::user()->id;
            if (in_array($adminId, [7, 11])) $content->body('暂未开放');
            else $content->body($this->guildWithdrawList());
        });
    }

    /**
     * 列表
     * @return Grid
     */
    protected function guildWithdrawList(): Grid
    {
        $grid = new Grid(new GuildWithdrawal());
        $where = [
            // ['status', Withdraw::STATUS_ING]
        ];
        if (request()->status == null) {
            request()->merge(['status' => GuildWithdrawal::STATUS_ING]);
        }
        $grid->model()->where($where)->orderBy('id', 'desc');
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new UpdateGuildWithdrawOk());
            $tools->append(new UpdateGuildWithdrawFail());
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });
        $grid->id('记录ID');
        $grid->userProfile()->user_profile_id('用户ID')->display(function ($data) {
            return "{$data}（内部ID：{$this->user_id}）";
        });
        $grid->userProfile()->nick_name('昵称');
        $grid->userProfile()->gender('性别')->display(function ($gender) {
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->guildProfile()->name('推广员名');

        $grid->withdraw_real_name('提款人姓名');
        $grid->withdraw_id_card('提款人身份证号');

        $grid->account('提款账号')->display(function ($data){
            return $this->withdraw_type == 1 ? $this->withdraw_account . '(银行卡)' :  $this->withdraw_account . '(支付宝)';
        });
        $grid->withdraw_type('提现账号类型')->display(function ($data) {
            return GuildWithdrawal::getAccountType($data);
        });

        $grid->withdraw_rmb('提现金额')->totalRow(function ($data) {
            return "<span class='text-danger text-bold'>总金币：{$data}</span>";
        });
        $grid->service_charge('提现手续费')->display(function ($data) {
            return bcmul($data,100,2) . '%';
        });
        $grid->reality_rmb('到账金额')->totalRow(function ($data) {
            return "<span class='text-danger text-bold'>总额：<i class='fa fa-yen'></i>" . round($data, 1) . "</span>";
        });
        $grid->withdraw_account_type('到账方式')->display(function ($data) {
            return GuildWithdrawal::TO_ACCOUNT_TYPE[$data];
        });
        $grid->created_at('申请时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->updated_at('记录更新时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->yzh_order_id('代付三方单号');
        $grid->withdraw_way('结算渠道')->display(function ($data) {
            return GuildWithdrawal::getWithdrawWay($data);
        });
        $grid->account_type('到账账号类型')->display(function ($data) {
            return GuildWithdrawal::getAccountType($data);
        });
        $grid->subject('提现主体')->display(function ($data) {
            $account_type  =GuildWithdrawal::getAccountType($this->account_type);
            return empty($account_type) || $account_type == '未知' ? '未知' : GuildWithdrawal::getSubject($data);
        });
        $grid->out_trans_id('商户号提现交易号')->editable();
        $grid->status('处理结果')->display(function ($data) {
            $str = GuildWithdrawal::STATUS[$data];
            if ($data == GuildWithdrawal::STATUS_YZH_ERR && $this->yzh_detail) {
                $detail = json_decode($this->yzh_detail, true);
                $str = "提现异常：{$detail['detail']}（{$detail['status']}）";
            }
            return $str;
        });

        //禁用导出
         $grid->disableExport();

        //禁用行选择
//        $grid->disableRowSelector();
        // $grid->disableActions();
         $grid->disableCreateButton();

        $grid->exporter(new WithdrawExport($grid));
        $grid->filter(function ($filter) {
            $filter->expand();
            // $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('guildProfile.guild_id', '公会ID');
                $filter->between('updated_at', '审核时间')->datetime();
                $filter->equal('withdraw_way', '结算渠道')->select(GuildWithdrawal::WITHDRAW_WAY);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('status', '审核状态')->select(GuildWithdrawal::STATUS);
                $filter->between('reality_rmb', '打款金额');
                $filter->equal('subject', '支付主体')->select(GuildWithdrawal::SUBJECT);
                $filter->equal('withdraw_account_type', '到账方式')->select(GuildWithdrawal::TO_ACCOUNT_TYPE);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->between('created_at', '提交时间')->datetime();
                $filter->equal('yzh_order_id', '云账户订单');
                $filter->equal('account_type', '收款方式')->select(GuildWithdrawal::ACCOUNT_TYPE);
            });

        });

        $isAdmin = $this->isAdmin;
        $adminUid = Admin::user()->id;
        $withdrawalBtUid = config('busi.withdrawal_bt_uid') ? config('busi.withdrawal_bt_uid') : [];

        $grid->actions(function (Grid\Displayers\Actions $actions) use ($isAdmin,$adminUid,$withdrawalBtUid) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
            if ($isAdmin || in_array($adminUid,$withdrawalBtUid)) {
                $actions->append(new GuildWithdrawVerify(
                    $actions->getKey(),
                    $actions->row,
                    'guild_withdraw/verify'
                ));
            }
        });

//        $grid->batchActions(function ($batch) {
//            $batch->add(new WithdrawVerfyOk());
//        });
        return $grid;
    }

    /**
     * 表单按钮的验证操作
     * @return array|false
     */
    public function verify(){
        $this->id = request('id');
        $this->status = request('status');
        if (!$this->id || !$this->status){
            return ['ret' => -1, 'message' => '操作不存在!!'];
        }

        $this->record = GuildWithdrawal::find($this->id);
        if (!$this->record){
            return ['ret' => -1, 'message' => '记录不存在'];
        }

        if ($this->record->status == $this->status) {
            return ['ret' => -1, 'message' => '该记录已经操作过，无法重复操作'];
        }

        if (
            $this->record->out_trans_id
            &&
            ($this->status == GuildWithdrawal::STATUS_FAIL || request('extra') == 'yzh')
        ) {
            return ['ret' => -1, 'message' => '已填写交易单号，无法进行该操作'];
        }

        $balanceInfo = GuildBalance::where('user_id',$this->record->user_id)->first();
        if (empty($balanceInfo)){
            return ['ret' => -1, 'message' => '用户不存在'];
        }

        try {
            //开启事物
            DB::beginTransaction();
            switch ($this->status){
                case GuildWithdrawal::STATUS_FAIL:
                    if ($this->record->out_trans_id) {
                        return ['ret' => -1, 'message' => '已填写商户号提现交易号，无法进行该操作～'];
                    }

                    GuildWithdrawal::where('id', $this->id)->limit(1)->update(['status' => $this->status]);


                    //退还账户余额 手续费也退回
                    GuildBalance::where('user_id',$this->record->user_id)->update([
                        'have_access_balance' => $balanceInfo->have_access_balance + $this->record->withdraw_rmb
                    ]);


                    DB::commit();

                    $this->pushToUser();

                    return ['ret' => 0, 'message' => '退还成功！'];
                case GuildWithdrawal::STATUS_OK:
                    //判断账号状态
                    $userInfo = User::where('id',$this->record->user_id)->first();
                    if($userInfo->status != 0 ){
                        $str =  $userInfo->status == 1 ? '该用户已被冻结，无法正常提现' : '该用户已注销，无法正常提现';
                        DB::rollBack();
                        return ['ret' => -1, 'message' => $str];
                    }

                    //判断公会状态
                    $guildInfo = GuildManage::getInfoByUserId($this->record->user_id);
                    if ($guildInfo->status != 1){
                        DB::rollBack();
                        return ['ret' => -1, 'message' => '该公会已经被冻结，无法正常提现'];
                    }

                    $this->payWay = request('extra');
                    if (empty($this->payWay)){
                        DB::rollBack();
                        return ['ret' => -1, 'message' => '操作不存在！！'];
                    }

                    $res = $this->withdrawMain();

                    if ($res['ret'] == -1){
                        DB::rollBack();
                        return $res;
                    }
                    DB::commit();
                    return $res;
                default:
                    DB::rollBack();
                    return ['ret' => -1, 'message' => '操作不存在！！'];
            }
        } catch (Exception $e) {
            DB::rollBack();
            Log::info(__CLASS__ . "==WithdrawId:{$this->id}==Exception:" . $e->getMessage());
            return ['ret' => -1, 'message' => '提现提交异常！'];
        }
    }

    /**
     * 给用户发送提现失败的消息
     * @return void
     */
    private function pushToUser()
    {
        $action = request('action');

        if ($action != 'yzh_err_back'){
            Message::pushSystem($this->record->user_id, '你的提现申请暂不通过！如有疑问，请联系在线客服', '提现通知');
            return;
        }

        $msg = "提现金额已退还，请重新校对信息后再申请提现～";
        if (!empty($this->record->yzh_detail)){
            $detail = json_decode($this->record->yzh_detail, true);
            $msg = "你的{$detail['detail']}，提现金额已退还，请重新校对信息后再申请提现～";
        }

        Message::pushSystem($this->record->user_id, $msg, '提现通知');
    }


    /**
     * 提现主要操作
     * @return array|false
     */
    private function withdrawMain()
    {
        $withdrawWay = '';
        switch ($this->payWay) {
            case 'yzh':
                $ret = GuildWithdrawal::doYzhOrder($this->record->toArray());
                $withdrawWay = isset($ret['bind_type']) && $ret['bind_type'] == GuildWithdrawal::WITHDRAW_TYPE_ALI ? '支付宝' : '银行卡';
                Log::info(__CLASS__ . "WithdrawId:{$this->id}==Payway:{$this->payWay}==UserId:{$this->record->user_id}==" . json_encode($ret));
                break;
            case 'yzh_xmi':
                $ret = GuildWithdrawal::doYzhOrder($this->record->toArray(),'yzh_xmi');
                $withdrawWay = isset($ret['bind_type']) && $ret['bind_type'] == GuildWithdrawal::WITHDRAW_TYPE_ALI ? '支付宝' : '银行卡';
                Log::info(__CLASS__ . "WithdrawId:{$this->id}==Payway:{$this->payWay}==UserId:{$this->record->user_id}==" . json_encode($ret));
                break;
            default:
                $ret = ['ret' => -1, 'message' => "payWay不正确", 'bind_type' => 0];
                Log::info(__CLASS__ . "WithdrawId:{$this->id}==Payway:{$this->payWay}==UserId:{$this->record->user_id}");
        }
        //提现审核没有通过
        if ($ret['ret'] != 0) {
            return $ret;
        }

        $time = date('Y年m月d日', strtotime((string)$this->record->created_at));
        $pushMsg = "你于{$time}申请的提现已通过审核，请注意查收你的{$withdrawWay}账号！";
        Message::pushSystem($this->record->user_id, $pushMsg, '提现通知');

        GuildWithdrawal::where('id', $this->id)->limit(1)->update([
            'status' => $this->status,
            'withdraw_way' => $this->payWay
        ]);

        return $ret;
    }
}
